<template>
  <div class="import">
    <upload-excel :beforeUpload="beforeUpload" :onSuccess="onSuccess">
    </upload-excel>
  </div>
</template>

<script>
import { importEmp } from "@/api/employees";
import moment from "moment";
export default {
  methods: {
    beforeUpload(file) {
      // console.log(file.size);
      if (file.size > 1024 * 2 * 1024) {
        this.$message.error("文件大小不能超过2M");
        return false;
      }
      return true;
    },
    async onSuccess({ header, results }) {
      // console.log(results);
      const userRelations = {
        入职日期: "timeOfEntry",
        手机号: "mobile",
        姓名: "username",
        部门: "departmentName",
        转正日期: "correctionTime",
        工号: "workNumber",
        聘用形式: "formOfEmployment",
      };
      let list = results.map((item) => {
        console.log(item);
        let newObj = {};
        for (const key in item) {
          let engKey = userRelations[key];
          if (key == "入职日期" || key == "转正日期") {
            let excelTime = item[key];
            // 转成JS时间
            let date = new Date((excelTime - 1) * 24 * 60 * 60 * 1000);
            let year = date.getFullYear();
            date.setFullYear(year - 70);
            date = moment().format("YYYY-MM-DD");
            newObj[engKey] = date;
          } else {
            // 把原来对象里的值赋值给新对象，并且是存到新的英文键对应的属性上
            newObj[engKey] = item[key];
          }
        }
        return newObj;
      });
      console.log(list);
      await importEmp(list);
      this.$message.success("导入数据成功!");
      this.$router.back();
    },

    // async success({ header, results }) {
    //   const userRelations = {
    //     入职日期: "timeOfEntry",
    //     手机号: "mobile",
    //     姓名: "username",
    //     转正日期: "correctionTime",
    //     工号: "workNumber",
    //   };
    //   const arr = [];
    //   results.forEach((item) => {
    //     const userInfo = {};
    //     Object.keys(item).forEach((key) => {
    //       userInfo[userRelations[key]] = item[key];
    //     });
    //     arr.push(userInfo);
    //   });
    //   let res = await importEmp(arr);
    //   console.log(res);
    // },
  },
};
</script>

<style>
</style>